package com.bruce.tool.search.solr.domain;

import com.bruce.tool.common.exception.BaseRuntimeException;
import com.bruce.tool.common.util.ClassUtils;
import com.bruce.tool.common.util.string.StringUtils;
import com.bruce.tool.search.solr.exception.SearchErrorCode;
import com.google.common.collect.Lists;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * 功能 :
 * solr查询标准参数
 * @author : Bruce(刘正航) 上午2:00 2018/5/8
 */
@NoArgsConstructor(staticName = "build")
public class FilterQuerys implements Serializable {

    /**查询类型:1(正向查询),-1(排除)**/
    private Set<FilterQuery> querys = new HashSet<>();

    /**只有一个值的条件**/
    public FilterQuerys addOne(String key, Object value){
        if( !ClassUtils.isBaseDataType(value.getClass()) ){
            throw new BaseRuntimeException(SearchErrorCode.QUERY_VALUE_NOT_SUPPORT.getCode(),SearchErrorCode.QUERY_VALUE_NOT_SUPPORT.getMessage());
        }
        return this.addAll(key,FilterQuery.FORWARD, Lists.newArrayList(value));
    }
    /**添加区域过滤条件**/
    public FilterQuerys addRange(String key, Integer left, Integer right){
        if( !ClassUtils.isBaseDataType(left.getClass())||!ClassUtils.isBaseDataType(right.getClass()) ){
            throw new BaseRuntimeException(SearchErrorCode.QUERY_VALUE_NOT_SUPPORT.getCode(),SearchErrorCode.QUERY_VALUE_NOT_SUPPORT.getMessage());
        }
        String value = "["+left+" TO "+right+"]";
        return this.addAll(key,FilterQuery.FORWARD, Lists.newArrayList(value));
    }
    /**
     * 添加区域过滤条件
     * begin和end 可以是[100 TO 200]或者(100 TO 200]或者[100 TO 200)或者(100 TO 200)
     * begin="[100"
     * begin="(100"
     * end="200]"
     * end="200)"
     */
    public FilterQuerys addRange(String key, String left, String right){
        if( !ClassUtils.isBaseDataType(left.getClass())||!ClassUtils.isBaseDataType(right.getClass()) ){
            throw new BaseRuntimeException(SearchErrorCode.QUERY_VALUE_NOT_SUPPORT.getCode(),SearchErrorCode.QUERY_VALUE_NOT_SUPPORT.getMessage());
        }
        String value = left+" TO "+right;
        return this.addAll(key,FilterQuery.FORWARD, Lists.newArrayList(value));
    }

    /**有多个值的条件**/
    public FilterQuerys addAll(String key, Collection<?> values){
        return this.addAll(key,FilterQuery.FORWARD,values);
    }
    /**有多个值的条件**/
    public FilterQuerys addAll(String key, Integer type, Collection<?> values){
        if( StringUtils.isBlank(key) ){
            throw new BaseRuntimeException(SearchErrorCode.QUERY_KEY_NON.getCode(),SearchErrorCode.QUERY_KEY_NON.getMessage());
        }
        this.querys.add(FilterQuery.build().addAll(key,type,values));
        return this;
    }

    public Collection<FilterQuery> queries(){
        return this.querys;
    }
}
